<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意:值允许为第三类分类设置相关参数!" type="warning" show-icon> </el-alert>

      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader clearable v-model="selectedCateKeys" :options="catelist" :props="({ expandTrigger: 'hover' }, cateProps)" @change="handleChange"></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数区域 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisableds" @click="addDialogVisible = true">添加参数</el-button>

          <!-- 表格区域 -->
          <el-table :data="manyTableData" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- tag标签 -->
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="handleChangeId(i, scope.row)">{{ item }}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="180"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteDialog(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态参数区域 -->
        <el-tab-pane label="静态属性" name="only" :disabled="isBtnDisableds">
          <el-button type="primary" @click="addDialogVisible = true">添加参数</el-button>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态展示对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="34%" @close="addParamsClose">
      <el-form :model="ParamsForm" :rules="ParamsFormRules" ref="ParamsFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="ParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑动态展示对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="editDialogVisible" width="34%">
      <el-form :model="editParmasForm" :rules="ParamsFormRules" ref="editParmasFormRef">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParmasForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      // 商品分类数组
      catelist: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定到的数组
      selectedCateKeys: [],
      // 被激活的页签的名称
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      addDialogVisible: false,
      editDialogVisible: false,
      // 天机动态展示的表单数据
      ParamsForm: {},
      // 添加参数的验证规则对象
      ParamsFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      // 编辑的表单数据
      editParmasForm: {}
    }
  },
  computed: {
    isBtnDisableds() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateID() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品参数失败')
      this.catelist = res.data
      console.log(res)
    },
    // 级联选择框选中项变化，会复发这个函数
    async handleChange() {
      this.getParamsData()
    },
    // tab页签点击事件的处理函数

    handleClick() {
      this.getParamsData()
    },

    async getParamsData() {
      // 证明选中的不是三级
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
      }
      // 证明选中的是三级
      // 动态参数请求6
      const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败')
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      console.log(res)
    },
    // 点击按钮，添加参数
    addParams() {
      this.$refs.ParamsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填必选项')
        const { data: res } = await this.$http.post(`categories/${this.cateID}/attributes`, {
          attr_name: this.ParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('创建失败')
        this.getParamsData()
        this.addDialogVisible = false
        this.$message.success('创建成功')
      })
    },
    // 监听添加参数对话框关闭事件
    addParamsClose() {
      this.$refs.ParamsFormRef.resetFields()
    },
    // 文本失去焦点会触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      this.saveAttrVals(row)
    },
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败')
      }
      this.$message.success('修改参数项成功')
    },
    // 点击按钮，展示文本输入框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
      console.log('oooo', row)
    },
    // 监听tag标签删除对应的参数可选项
    async handleChangeId(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 点击编辑按钮 弹出对话框
    async showEditDialog(rowID) {
      const { data: res } = await this.$http.get(`categories/${this.cateID}/attributes/${rowID}`)
      if (res.meta.status !== 200) return this.$message.error('id查询失败')
      console.log(res)
      this.editParmasForm = res.data
      this.editDialogVisible = true
    },
    // 点击编辑确认 修改
    editParams() {
      this.$refs.editParmasFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填必选项')
        const { data: res } = await this.$http.put(`categories/${this.cateID}/attributes/${this.editParmasForm.attr_id}`, {
          attr_name: this.editParmasForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(`更新${this.titleText}失败`)
        this.getParamsData()
        this.editDialogVisible = false
        this.$message.success(`更新${this.titleText}成功`)
      })
    },
    // id查询删除对应的id属性
    async deleteDialog(rowID) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除!')
      const { data: res } = await this.$http.delete(`categories/${this.cateID}/attributes/${rowID}`)
      if (res.meta.status !== 200) return this.$message.error(`删除${this.titleText}失败`)
      this.getParamsData()
      this.$message.success(`删除${this.titleText}成功`)
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 300px;
}
</style>
